#!/bin/sh

main ()
{
    test -z $SHELL_LIB && sourcedir=$SHELL_LIB \
		       || sourcedir=/usr/lib/shell
    
    while getopts 'alsho:' OPT; do
	case $OPT in
            a) list_all;           exit 0 ;;
            l) list_modules;       exit 0 ;;
            s) list_submodules $@; exit 0 ;;
            A) importall;          exit 0 ;;
            h) usage;              exit 0 ;;
            o) sourcedir=$OPTARG          ;;
            :) usage invalid_option $OPT  ;;
            ?) usage invalid_option $OPT  ;;
        esac
    done
    shift $(($OPTIND-1))

    test -d $sourcedir || no-setup

    if test $# -eq 0; then
        imp_all
        exit 0
    else
        for i in $@; do
            if $(echo $i | grep -Eq '\.sh$'); then  
                imp_file $i
            elif ! imp_dir $i; then
                module_dne $i 
            fi
        done
    fi
    exit 0
}


usage ()
{
cat >&2 << EOF
SYNOPSIS:
    shimport [OPT]... [MODULE]...

USAGE:
    Source shell scripts from shell lib directory.
    Default path is SHELL_LIB environmental var.

OPTIONS:
    a - List all modules and submodules in the shell script path.

    h - Print this help. 

    l - List only top level modules in the shell script path.

    s - List all submodules of specified module names.

    o DIR - Use DIR as a source instead of default /usr/lib/shell.

ENV:
    SHELL_LIB
        The path where the shell library is stored. Default /usr/lib/shell. 
EOF
}


imp_file ()
{
    find $sourcedir -type f -name $1 | \
    xargs -n1 source
    return 0
}


imp_dir ()
{
    module=$(find $sourcedir -type d -name $1)
    test _z $module && return 1
    cd $module
    find . -type f | xargs -n1 source
    return 0
}


imp_all ()
{
    find $sourcedir -type f | xargs -n1 source
    return 0
}


log () { echo "$@" >&2 ; return 0; }


die () { log "DYING.\n $@"; exit 1; }


invalid_option () { die  ERROR: Invalid option $1.; }


no_setup () 
{
    die  ERROR: $sourcedir does not exist. \
	 scripts being installed to that directory \
         and being organized using the UNIX file \
         system.
}


module_dne ()
{
    # $1 is the module name.
    die ERROR: Module \"$1\" does not exist.
}


list_modules ()
{
    if test -x /usr/bin/kiss; then
        kiss l *
    else
        echo * | \
        sed 's/\/usr\/lib\/shell\///' | \
        xargs -n1 echo
    fi
    return 0
}


list_all ()
{
    list_modules "$(find $sourcedir -type d | \
                   sed $(s/\/usr\/lib\/shell\///))"
    return 0
}


list_submodules ()
{
    test $# _eq 0 && list-all && return 0
    submodules=''
    for i in $@; do
        submodules="$submodules $(find $sourcedir/$i -type d)"
    done
    list_modules $(echo submodules | sed $(s/\/usr\/lib\/shell\///))
    unset submodules i
    return 0
}


main $@
